import { _decorator, Animation } from 'cc';
import { PARAME_NAME_ENUM } from '../../Enums';
import State from '../Base/State';
import {  getInitParamsTrigger, StateMachine } from '../Base/StateMachine';
const { ccclass } = _decorator;


@ccclass('NpcPlayerStateMachine')
export class NpcPlayerStateMachine extends StateMachine {
    private source = []
    private roleType = []
    private whiteList = []
    private callback
    init(source = []) {
        this.source = source
        this.animationComponent = this.addComponent(Animation)
        this.initStateMachinesOrParams()
        this.initAnimationEvent()
    }
    initStateMachinesOrParams() {
        this.source.forEach(item => {
            if (!item.type.includes('idle')&&!item.type.includes("avoid")) {
                this.whiteList.push(item.name)
            }
            this.roleType.push(item.type)
            this.params.set(item.type, getInitParamsTrigger())
            this.stateMachines.set(item.type, new State(this, item.spriteList, item.wrapMode, item.name,item.animation_speed))
        })
    }
    // 动画状态事件
    initAnimationEvent() {
        this.animationComponent.on(Animation.EventType.FINISHED, () => {
            const name = this.animationComponent.defaultClip.name
            if (this.whiteList.some(v => name==v)) {
                this.setParams(PARAME_NAME_ENUM.IDLE, true)
            }
        })
    }
    run() {
        clearTimeout(this.callback)
        this.roleType.forEach(item => {
            if (this.params.get(item).value) {
                this.currentState = this.stateMachines.get(item)
            } else {
                this.currentState = this.currentState
            }
        })

    }

    pause() {
        this.callback = setTimeout(() => {
            this.animationComponent.pause()
        }, 20)
    }
}


